<template>
  <Row id="medicalUserWork" type="flex" justify="center" :gutter="24" class="panel">
    <Col>
    <Tag type="dot" :color="NORMAL_COLOR">治疗设备1</Tag>
    <Tag type="dot" :color="USED_COLOR">治疗设备2</Tag>
    <Tag type="dot" :color="DISABLED_COLOR">治疗设备3</Tag>
    <Tag>事件持续时间40分钟</Tag>
    </Col>
    <Col>
    <div class="calendar">
      <Row type="flex">
        <Col>
        <Form inline>
          <FormItem prop="name">
            <Select clearable placeholder="姓名" style="width: 150px;" v-model="params.userId">
              <Option v-for="item in users" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem prop="name">
            <Button @click="search">查询</Button>
          </FormItem>
          <FormItem>
            <Button @click="handleAddSchedule" type="primary">新增排班</Button>
          </FormItem>
        </Form>
        </Col>
      </Row>
      <FullCalendar ref="fullCalendar" :options="calendarOptions"></FullCalendar>
      <save-schedule :visible="saveVisible" :userId="params.userId" :date="selectDate" @on-close="saveVisible = false"
        :clickedDateTime="clickedDateTime" @on-success="search"></save-schedule>
      <view-schedule :visible="viewVisible" :id="selectId" @on-close="viewVisible = false"
        @on-refresh="search"></view-schedule>
    </div>
    </Col>
  </Row>
</template>

<script>
import FullCalendar from '@fullcalendar/vue';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import listPlugin from '@fullcalendar/list';
import mockData from './mock'
import SaveSchedule from "./save-schedule";
import ViewSchedule from "./view-schedule";
import moment from 'moment';
import Vue from 'vue';
Vue.prototype.$moment = moment;
export default {
  name: 'FullCalendarDemo',
  components: { ViewSchedule, SaveSchedule, FullCalendar },
  data() {
    return {
      DISABLED_COLOR: '#c5c8ce',
      USED_COLOR: '#19be6b',
      NORMAL_COLOR: '#2db7f5',
      calendarOptions: {
        plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin],
        initialView: 'dayGridMonth',
        locale: 'zh',
        firstDay: 1,
        // 时间轴间距
        slotMinTime: '8:00',
        slotMaxTime: '18:00',
        slotDuration: '00:15:00',
        defaultTimedEventDuration: '00:40',
        // 月视图，是否为指定周数高度，true 6周高度
        fixedWeekCount: false,
        // 月视图，是否显示非本月日期
        showNonCurrentDates: false,
        // 是否显示全天插槽
        allDaySlot: false,
        weekends: true,
        dayMaxEvents: true,
        slotLabelFormat: {
          hour: 'numeric',
          minute: '2-digit',
          hour12: false
        },
        eventTimeFormat: {
          hour: 'numeric',
          minute: '2-digit',
          hour12: false
        },
        buttonText: {
          today: '今天',
          month: '月',
          week: '周',
          day: '日',
          list: '周列表'
        },
        headerToolbar: {
          left: 'prev,next today',
          center: 'title',
          right: 'dayGridMonth,timeGridWeek,timeGridDay listWeek'
        },
        validRange: this.validRange,
        events: [],
        datesSet: this.datesSet,
        eventClick: this.handleEventClick,
        dateClick: this.handleDateClick,
        eventDidMount: this.handleEventDidMount,
      },
      validRange: {
        start: '2019-01-01',
        end: this.$moment().add(6, 'months').format('YYYY-MM-DD')
      },
      users: [],
      params: {},
      viewVisible: false,
      selectId: 0,
      selectDate: '',
      saveVisible: false,
      clickedDateTime: '',
    };
  },
  methods: {
    getColor(event) {
      // 默认可预约
      let color = this.NORMAL_COLOR;
      if (event.state === 2) {
        // 已禁用
        color = this.DISABLED_COLOR;
      } else if (event.state === 1) {
        // 已预约
        color = this.USED_COLOR;
      }
      return color;
    },
    init() {
      this.params.startDate = this.$moment().startOf('month').format('YYYY-MM-DD HH:mm:ss');
      this.params.endDate = this.$moment().endOf('month').format('YYYY-MM-DD HH:mm:ss');
      this.users = mockData.users
      this.search();
    },
    search() {
      this.calendarOptions.events = [];
      mockData.schedules.filter(item => {
        let isUser = true;
        if (this.params.userId) {
          isUser = item.userId === this.params.userId;
        }
        let isAfter = this.$moment(item.date).isAfter(this.params.startDate);
        let isBefore = this.$moment(item.date).isBefore(this.params.endDate);
        return isUser && isAfter && isBefore;
      }).forEach(item => {
        let color = this.getColor(item);
        this.calendarOptions.events.push({
          backgroundColor: color,
          borderColor: color,
          title: mockData.getUserName(item.userId),
          start: item.date,
          extendedProps: item
        });
      });
    },
    datesSet(info) {
      let date = info.view.activeStart;
      // 查询月份数据
      this.params.startDate = this.$moment(date).startOf('month').format('YYYY-MM-DD HH:mm:ss');
      this.params.endDate = this.$moment(date).endOf('month').format('YYYY-MM-DD HH:mm:ss');
      this.search();
    },
    handleDateClick(arg) {
      this.selectDate = this.$moment(arg.date).startOf('day').format('YYYY-MM-DD HH:mm:ss');
      // 将点击的日期和时间存储在 clickedDateTime 中
      this.clickedDateTime = this.$moment(arg.date).format('YYYY-MM-DD HH:mm:ss');
      this.saveVisible = true;
    },
    handleEventClick(info) {
      this.selectId = info.event.extendedProps.id;
      this.viewVisible = true;
    },
    //鼠标悬浮卡片
    // handleEventDidMount(info) {
    //   const eventEl = info.el;
    //   // 创建一个 div 元素作为卡片
    //   const card = document.createElement('div');
    //   // card.className = 'event-card';
    //   card.style.position = 'absolute';
    //   card.style.display = 'none';
    //   // 优化卡片样式
    //   card.style.backgroundColor = '#fff';
    //   card.style.border = '1px solid #ebeef5';
    //   card.style.borderRadius = '4px';
    //   card.style.boxShadow = '0 2px 12px 0 rgba(0, 0, 0, 0.1)';
    //   card.style.padding = '10px';
    //   card.style.zIndex = '9999';
    //   card.style.width = '210px';
    //   card.style.display = 'flex';
    //   card.style.flexDirection = 'column';
    //   card.style.gap = '10px';
    //   // 将卡片添加到文档中
    //   document.body.appendChild(card);

    //   eventEl.addEventListener('mouseenter', (e) => {
    //     // 显示卡片
    //     requestAnimationFrame(() => {
    //       card.style.display = 'block';
    //       // 计算卡片的位置
    //       const rect = eventEl.getBoundingClientRect();
    //       const viewportWidth = window.innerWidth;
    //       // 使用 getComputedStyle 获取卡片的宽度
    //       const computedStyle = getComputedStyle(card);
    //       const cardWidth = parseFloat(computedStyle.width);
    //       // 检查卡片是否会超出视口右侧
    //       if (rect.left + rect.width + cardWidth + 10 > viewportWidth) {
    //         // 如果超出，将卡片显示在事件元素的左侧
    //         card.style.left = `${rect.left - cardWidth - 10}px`;
    //       } else {
    //         card.style.left = `${rect.left + rect.width + 10}px`;
    //       }
    //       card.style.top = `${rect.top}px`;
    //       // 填充卡片内容，这里可以根据你的需求添加更多信息
    //       card.innerHTML = `
    //         <div class="card-header" style="font-size: 15px; font-weight: bold; border-bottom: 1px solid #ebeef5; padding-bottom: 4px;">
    //           事件详情
    //         </div>
    //         <div class="card-body">
    //           <p><span style="color: #606266;">用户ID:</span> ${info.event.extendedProps.userId}</p>
    //           <p><span style="color: #606266;">日期:</span> ${info.event.startStr}</p>
    //           <p><span style="color: #606266;">状态:</span> ${info.event.extendedProps.state}</p>
    //         </div>
    //       `;
    //     });
    //   });

    //   eventEl.addEventListener('mouseleave', () => {
    //     // 隐藏卡片
    //     card.style.display = 'none';
    //   });
    // },

//     handleEventDidMount(info) {
//   const eventEl = info.el;
//   // 创建一个 div 元素作为卡片
//   const card = document.createElement('div');
//   // 优化卡片样式
//   card.style.position = 'absolute';
//   card.style.display = 'none';
//   card.style.backgroundColor = '#fff';
//   card.style.border = '1px solid #ebeef5';
//   card.style.borderRadius = '4px';
//   card.style.boxShadow = '0 2px 12px 0 rgba(0, 0, 0, 0.1)';
//   card.style.padding = '10px';
//   card.style.zIndex = '9999';
//   card.style.width = '210px';
//   card.style.display = 'flex';
//   card.style.flexDirection = 'column';
//   card.style.gap = '10px';
//   // 将卡片添加到事件元素中，避免影响全局布局
//   eventEl.appendChild(card);

//   eventEl.addEventListener('mouseenter', (e) => {
//     this.showCard(card, eventEl, info);
//   });

//   eventEl.addEventListener('mouseleave', () => {
//     this.hideCard(card);
//   });
// },
// showCard(card, eventEl, info) {
//   requestAnimationFrame(() => {
//     card.style.display = 'block';
//     // 计算卡片的位置
//     const rect = eventEl.getBoundingClientRect();
//     const viewportWidth = window.innerWidth;
//     // 使用 getComputedStyle 获取卡片的宽度
//     const computedStyle = getComputedStyle(card);
//     const cardWidth = parseFloat(computedStyle.width);
//     // 检查卡片是否会超出视口右侧
//     if (rect.left + rect.width + cardWidth + 10 > viewportWidth) {
//       // 如果超出，将卡片显示在事件元素的左侧
//       card.style.left = `${rect.left - cardWidth - 10}px`;
//     } else {
//       card.style.left = `${rect.left + rect.width + 10}px`;
//     }
//     card.style.top = `${rect.top}px`;
//     // 填充卡片内容，这里可以根据你的需求添加更多信息
//     card.innerHTML = `
//       <div class="card-header" style="font-size: 15px; font-weight: bold; border-bottom: 1px solid #ebeef5; padding-bottom: 4px;">
//         事件详情
//       </div>
//       <div class="card-body">
//         <p><span style="color: #606266;">用户ID:</span> ${info.event.extendedProps.userId}</p>
//         <p><span style="color: #606266;">日期:</span> ${info.event.startStr}</p>
//         <p><span style="color: #606266;">状态:</span> ${info.event.extendedProps.state}</p>
//       </div>
//     `;
//   });
// },
// hideCard(card) {
//   card.style.display = 'none';
//   // 移除卡片，避免影响其他元素
//   if (card.parentNode) {
//     card.parentNode.removeChild(card);
//   }
// },

    //点击新增排班
    handleAddSchedule() {
      this.saveVisible = true;
    }
  },
  mounted() {
    this.init();
  }
};
</script>

<style>
#medicalUserWork .ivu-tag {
  display: block;
}
</style>

<style scoped>
.panel {
  padding-top: 64px;
}

.calendar {
  width: 820px;
  height: 800px;
}

.fc {
  --fc-small-font-size: 0.8rem;
}

/deep/.fc table {
  font-size: 1.1em;
}
</style>
